using System;
using System.ComponentModel;
using System.Linq;
using System.Collections.Generic;
using System.Data.Metadata.Edm;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Reflection;
using Microsoft.Practices.ObjectBuilder2;
using Common.Core;
using Guard=Common.Core.Guard;

namespace Common.Unity.Extensions.Entity
{
	public class EntityCreator : EntityContextCreatorBase<ObjectContext>
	{
		readonly bool addOnCreate;

		public EntityCreator( ObjectContext context ) : this( context, true )
		{}

		public EntityCreator( ObjectContext context, bool addOnCreate ) : base( context )
		{
			this.addOnCreate = addOnCreate;
		}

		protected override void OnCreated( object instance )
		{
			if ( addOnCreate )
			{
				var type = instance.GetType();
				var name = MetadataHelper.ResolveEntitySet( EntityContext, type ).Name;
				EntityContext.AddObject( name, instance );
			}
		}
	}
}